import os
import shutil
import time
from pathlib import Path

import cv2
import torch
from numpy import random
from utils.general import (check_img_size, non_max_suppression, scale_coords, xyxy2xywh)
from utils.plots import plot_one_box
from utils.torch_utils import time_synchronized
from utils.datasets import LoadStreams, LoadImages
from utils.torch_utils import select_device
from configs.flask_id2name import id2name


def yolo_predict_ret_img(opt, model, img, img_path, showFlaws):
    out, source, view_img, save_img, save_txt, imgsz, counts = \
        opt['output'], opt['source'], opt['view_img'], opt['save_img'], opt['save_txt'], opt['imgsz'], opt['counts']
    boxes_detected = []

    # Initialize
    device = select_device(opt['device'])  # 选择设备
    if os.path.exists(out):
        shutil.rmtree(out)
    os.makedirs(out)
    half = device.type != 'cpu'

    imgsz = check_img_size(imgsz, s=model.stride.max())  # check img_size
    if half:
        model.half()  # to FP16

    # Set Dataloader
    dataset = LoadImages(img_path, img_size=imgsz)

    # Get names and colors
    names = model.module.names if hasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]

    # Run inference
    img = torch.zeros((1, 3, imgsz, imgsz), device=device)  # init img
    _ = model(img.half() if half else img) if device.type != 'cpu' else None  # run once
    for path, img, im0s, _ in dataset:
        img = torch.from_numpy(img).to(device)
        img = img.half() if half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        # Inference
        t1 = time_synchronized()

        # 前向推理
        pred = model(img, augment=opt['augment'])[0]
        # Apply NMS（非极大抑制）
        print(f"conf_thres:{opt['conf_thres']},iou_thres:{opt['iou_thres']}")
        pred = non_max_suppression(pred, opt['conf_thres'], opt['iou_thres'], classes=opt['classes'],
                                   agnostic=opt['agnostic_nms'])

        t2 = time_synchronized()

        # Process detections
        for i, det in enumerate(pred):  # detections per image
            p, s, im0 = path, '', im0s
            save_path = str(Path(out) / Path(p).name)  # 保存路径
            txt_path = str(Path(out) / Path(p).stem) + ('_%g' % dataset.frame if dataset.mode == 'video' else '')
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            if det is not None and len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += '%g %ss, ' % (n, names[int(c)])  # add to string

                # Write results
                boxes_detected = []  # 检测结果
                for *xyxy, conf, cls in reversed(det):
                    # counts += 1
                    xyxy_list = (torch.tensor(xyxy).view(1, 4)).view(-1).tolist()

                    # 如果不在要显示的缺陷种类里,则跳过
                    if int(cls.item()) not in showFlaws:
                        continue
                    if opt['thresh_model'][int(cls.item())] > conf:
                        continue

                    boxes_detected.append({"name": id2name[int(cls.item())],
                                           "conf": conf.item(),
                                           "bbox": [int(xyxy_list[0]), int(xyxy_list[1]), int(xyxy_list[2]),
                                                    int(xyxy_list[3])]
                                           })
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        with open(txt_path + '.txt', 'a') as f:
                            f.write(('%g ' * 5 + '\n') % (cls, *xywh))  # label format

                    # if save_img or view_img:  # Add bbox to image
                    label = '%s %.2f' % (names[int(cls)], conf)
                    plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=2)

            # Print time (inference + NMS)
            print('%sDone. (%.3fs)' % (s, t2 - t1))

            if save_img:
                if dataset.mode == 'images':
                    cv2.imwrite(save_path, im0)
    results = {"results": boxes_detected}

    # return im0
    return im0, results
